const timeStamp = second_time => { //秒转换成天时分秒
	var time = parseInt(second_time) + "";
	if (parseInt(second_time) > 60) {

		var second = parseInt(second_time) % 60;
		var min = parseInt(second_time / 60);
		time = min + ":" + second + "";

		if (min > 60) {
			min = parseInt(second_time / 60) % 60;
			var hour = parseInt(parseInt(second_time / 60) / 60);
			time = hour + ":" + min + ":" + second + "";

			if (hour > 24) {
				hour = parseInt(parseInt(second_time / 60) / 60) % 24;
				var day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
				time = day + ":" + hour + ":" + min + ":" + second + "";
			}
		}
	}
	return time;
}
const formatSeconds = (result) => {
	var h = Math.floor(result / 3600) < 10 ? '0'+Math.floor(result / 3600) : Math.floor(result / 3600);
	    var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
	    var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
	    return result = h + ":" + m + ":" + s;
}

const timeStamp_msec = leftTime => {
	var d, h, m, s, ms;
	if (leftTime >= 0) {
		d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
		h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
		m = Math.floor(leftTime / 1000 / 60 % 60);
		s = Math.floor(leftTime / 1000 % 60);
		ms = Math.floor(leftTime % 1000);
		ms = ms < 100 ? "0" + ms : ms
		s = s < 10 ? "0" + s : s
		m = m < 10 ? "0" + m : m
		h = h < 10 ? "0" + h : h
		return d + "：" + h + "：" + m + "：" + s + ":" + ms
	} else {
		console.log('已截止')
	}
}
const formatTime = date => {
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()
	return [hour, minute, second].map(formatNumber).join(':')
}
const formatDate = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	return [year, month, day].map(formatNumber).join('-')
}
const config = {
	globalData: {
		// apiUrl: 'https://www.yzdea.com',
		apiUrl: 'https://test.yzdea.com',
	}
}
let login_type = {

}
let C = (name) => { //获取配置
	return config.globalData[name] ? config.globalData[name] : '';
}
let O = { //对象合并
	extend: (o, n) => {
		for (var p in n) {
			if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p))) o[p] = n[p];
		}
		return o;
	},
}
let R = {
	showLoading(title, mask, time) { //加载提示
		return setTimeout(() => {
			uni.showLoading({
				title: title || '',
				mask: mask || true
			})
		}, time || 1000)
	},
	hideLoading(obj) {
		clearTimeout(obj)
		uni.hideLoading()
	},
	getImgurl() { //获取图标地址
		return 'https://oss.yzdea.com/app_img/';
	},
	encode(obj) { //json编码
		return encodeURIComponent(JSON.stringify(obj))
	},
	decode(obj) { //解析json编码
		return JSON.parse(decodeURIComponent(obj))
	},
	repmoney(obj) { //限制输入正确的金额！！！

		obj = obj.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
		obj = obj.replace(/^\./g, ""); //验证第一个字符是数字
		obj = obj.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
		obj = obj.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
		obj = obj.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
		return obj;

	},
	post: (items) => { // 网络请求方法
		let logindata = S.get('token')
		return new Promise((resolve, reject) => {
			if (typeof items == 'string') items = {
				url: items
			}
			if (!items.url) return console.log('缺少url参数.', items);
			if (!items.data) items.data = {};
			items.url = config.globalData.apiUrl + items.url;
			items.data.token = logindata || ''

			uni.request({
				url: items.url,
				method: 'POST',
				header: {
					'cache-control': true,
					'content-type': 'application/json'
				},
				responseType: items.responseType || 'text',
				data: items.data,
				complete: (res) => {


					// console.log(res)   
					if (res && res.data && res.data.status_code == 401) {

						S.cls('token')
						// uni.reLaunch({
						// 	url:'/pages/index/index'
						// })
						uni.reLaunch({
							url: '/pages/login/login'
						})
						// R.url('/pages/login/login')
						reject(res.data)
						// uni.hideNavigationBarLoading()
						return false
					}
					uni.hideNavigationBarLoading()
					false ? console.log('Server：' + items.url + '\n', res.data, '\nClient：',
						items.data) : '';
					resolve(res.data);
				}
			})
		})
	},
	// 判断版本号
	compareVersion: (ov, nv) => {
		if (!ov || !nv || ov == "" || nv == "") {
			return false;
		}
		var b = false,
			ova = ov.split(".", 4),
			nva = nv.split(".", 4);
		for (var i = 0; i < ova.length && i < nva.length; i++) {
			var so = ova[i],
				no = parseInt(so),
				sn = nva[i],
				nn = parseInt(sn);
			if (nn > no || sn.length > so.length) {
				return true;
			} else if (nn < no) {
				return false;
			}
		}
		if (nva.length > ova.length && 0 == nv.indexOf(ov)) {
			return true;
		}
	},
	upload: (items) => {
		return new Promise((resolve, reject) => {
			if (!items.url) return console.log('缺少url参数.', items);
			if (!items.file) return console.log('缺少file参数.', items);
			if (!items.data) items.data = {};
			var token = S.get('token')
			items.url = config.globalData.apiUrl + items.url;
			var ids = [];
			if (typeof items.file == 'object') {
				var promises = [];
				for (let i in items.file) {
					promises[i] = new Promise((resolve) => {
						uni.uploadFile({
							header: {},
							dataType: 'json',
							url: items.url,
							filePath: items.file[i],
							formData: {
								file: items.file[i],
								token: token
							},
							name: 'file',
							success: function(res) {
								let re = JSON.parse(res.data)
								if (re.status_code != 200) {
									R.toast(re.msg);
									return false
								}
								// config.debug ? console.log('Server：' + items.url + '\n', res.data, '\nClient：', items.data) : '';
								if (re.status_code == 200) {
									resolve(re);
								}
								// R.toast('已上传：' + (ids.length) + '张图');
							}
						})
					});
				}
				Promise.all(promises).then(res => {
					resolve(res)
				}).catch(err => {
					R.toast('图片上传失败');
				})
			} else {
				uni.uploadFile({
					header: {
						'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
					},
					url: items.url,
					filePath: items.file,
					name: 'image',
					formData: items.data,
					success: function(res) {
						let re = JSON.parse(res)
						resolve(re);
					}
				})
			}

		})
	},
	upData() {
		const updateManager = uni.getUpdateManager()
		updateManager.onCheckForUpdate(function(res) {
			// 请求完新版本信息的回调
			// console.log(res)
		})
		updateManager.onUpdateReady(function() {
			uni.showModal({
				title: '更新提示',
				content: '新版本已经准备好，是否重启应用？',
				success(res) {
					if (res.confirm) {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate()
					}
				}
			})
		})
		updateManager.onUpdateFailed(function() {
			// 新版本下载失败
			R.toast('更新失败，请重新启动')
		})
	},
	openimg: (option, sourceType) => {
		if (typeof option == 'number') option = {
			count: option
		}
		if (!option) option = {
			count: 1
		}
		var data = {
			sizeType: ['original', 'compressed'],
			sourceType: sourceType || ['album', 'camera']
		}
		data = O.extend(option, data);
		return new Promise((resolve, reject) => {
			data.success = (res) => {
					resolve(res)
				},
				data.fail = (err) => {
					//#ifdef APP-PLUS
					if (err.errCode == '-10' || err.errCode == 11 || err.errCode == 2) {
						R.Permission({
							iosType: 'camera',
							androidType: 'android.permission.CAMERA',
							msg: '手机暂未开启相机权限，是否开启'
						})
						R.Permission({
							iosType: 'photoLibrary',
							androidType: 'android.permission.READ_EXTERNAL_STORAGE',
							msg: '手机暂未开启相册权限，是否开启'
						})
					}
					//#endif
				}
			uni.chooseImage(data)
		});
	},
	login(msg) { //验证登录
		if (!uni.getStorageSync('token')) {
			return false
		} else {
			return true
		}
	},


	url: href => {
		if (typeof href != 'string') return console.log('缺少href参数.', href);
		uni.navigateTo({
			url: href
		})
	},
	back: (index = 1) => {
		if (typeof index != 'number') return console.log('缺少index参数.', index);
		uni.navigateBack({
			delta: index
		})
	},
	goto: href => {
		if (typeof href != 'string') return console.log('缺少href参数.', href);
		uni.redirectTo({
			url: href
		})
	},
	toast(msg, icon, mask) {
		uni.showToast({
			title: msg,
			icon: icon || 'none',
			mask: mask || true,
			position: 'bottom'
		})
	},
	/*获取当前页url*/
	getCurrentPage(num) {
		var pages = getCurrentPages() //获取加载的页面
		var currentPage = pages[pages.length - num] //1为当前页 2为上一页以此类推
		return currentPage
	},
	getLocation() { //获取当前位置信息
		return new Promise((resolve, reject) => {
			if (uni.getLocation) {
				let time = S.get('time');
				if (time) { //间隔30s定位一次 避免重复定位
					let Location = S.get('Location')
					if ((new Date().getTime() / 1000 - time) <= 30) {
						resolve(Location)
					} else if ((new Date().getTime() / 1000 - time) > 30) {
						resolve(Location)
						S.cls('time');
					}
					return false
				}
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (res) => {
						resolve(res)
						S.set('Location', res)
						S.set('time', new Date().getTime() / 1000);
					},
					fail: (res) => {
						console.log(res)
						reject(res)
						// #ifdef APP-PLUS
						R.Permission({
							iosType: 'location',
							androidType: 'android.permission.ACCESS_FINE_LOCATION',
							msg: '手机暂未开启定位权限，是否开启'
						})
						// #endif
						// #ifdef MP-WEIXIN
						if (res.errMsg == "getLocation:fail auth deny") {
							uni.showModal({
								title: '温馨提示',
								content: '请授权您的位置信息，以便为您提供服务',
								showCancel: true,
								success: (result) => {
									if (result.confirm) {
										uni.openSetting({
											success(ret) {
												if (ret.authSetting[
														'scope.userLocation'
													]) {
													R.getLocation()
												} else {
													reject(ret)
												}
											}
										})
									}

								},
								fail: (err) => {
									reject(err)
								}
							})
						}
						// #endif

					},
					complete: (res) => {},
				})

			} else {
				reject('当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。')
				uni.showModal({
					title: '提示',
					content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
				})
			}
		})
	},

}
// 本地缓存方法
let S = {
	get: (val) => {
		return uni.getStorageSync(val) || '';
	},
	set: (name, val) => {
		return uni.setStorageSync(name, val);
	},
	cls: (name) => {
		return uni.removeStorageSync(name);
	},
	getdate: (time) => {
		if (time.toString().length == 10) {
			time = Number(time) * 1000
		}
		var date = new Date(time);
		var y = date.getFullYear()
		var m = date.getMonth() + 1
		m = m < 10 ? '0' + m : m
		var d = date.getDate()
		d = d < 10 ? ('0' + d) : d
		return `${y}-${m}-${d}`
	},
	//判断时间戳是否为当前月
	isSameMonth: (time) => {
		if (time.toString().length == 10) {
			time = Number(time) * 1000
		}
		var nowDate = new Date()
		var date = new Date(time);
		return ((nowDate.getFullYear() == date.getFullYear()) &&
			(nowDate.getMonth() == date.getMonth())
		)
	}

}
const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}
//手机正则验证
let telReg = phone => {
	if (/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(phone)) {
		return true;
	}
	return false;
}
//密码验证
let pwdReg = pwd => {
	if (/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/.test(pwd)) {
		return true;
	}
	return false;
}
//时间戳格式年月日
const timestampToDate = timestamp => {
	let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	let Y = date.getFullYear() + '-';
	let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	let D = change(date.getDate()) + ' ';
	return Y + M + D
}
//时间戳格式年月日时分秒
const timestampToTime = timestamp => {
	let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	let Y = date.getFullYear() + '-';
	let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	let D = change(date.getDate()) + ' ';
	let h = change(date.getHours()) + ':';
	let m = change(date.getMinutes()) + ':';
	let s = change(date.getSeconds());
	return Y + M + D + h + m + s;

}
//时间戳13位
const formatter = date => {
	var date = new Date(date);
	var YY = date.getFullYear() + '-';
	var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	return YY + MM + DD;
}
const formatterForIos = date => {
	var date = new Date(date);
	var YY = date.getFullYear() + '/';
	var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
	var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	return YY + MM + DD 

}
//时间戳13位
const formattermonth = time => {
	var date = new Date(time);
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	month = month < 10 ? "0" + month : month;
	day = day < 10 ? "0" + day : day;
	return year + "-" + month
}
const formattermonthForIos = time => {
	var date = new Date(time);
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	month = month < 10 ? "0" + month : month;
	day = day < 10 ? "0" + day : day;
	return year + "/" + month
}
const getDate=()=>{
	let year = new Date().getFullYear();
	let month = new Date().getMonth() + 1;
	let day = new Date().getDate();
	month = month < 10 ? "0" + month : month;
	day = day < 10 ? "0" + day : day;
	return year + "/" + month + "/" + day
}
//处理时间戳格式
const change = t => {
	if (t < 10) {
		return "0" + t;
	} else {
		return t;
	}
}
module.exports = {
	R: R,
	S: S,
	O: O,
	formatTime: formatTime,
	formatDate: formatDate,
	timeStamp: timeStamp,
	timeStamp_msec: timeStamp_msec,
	telReg: telReg,
	config: config,
	pwdReg: pwdReg,
	timestampToDate: timestampToDate,
	timestampToTime: timestampToTime,
	formatter: formatter,
	formatterForIos: formatterForIos,
	formattermonth: formattermonth,
	formattermonthForIos: formattermonthForIos,
	formatSeconds:formatSeconds,
	getDate:getDate
}
